package k8s

import (
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	"fmt"

	"log"
	"strings"
	"strconv"
)

type Namespace struct {
	Name string				`json:"name"`
	Staus string			`json:"status"`
	CreateDate string		`json:"createdate"`
}

func GetKubernetesNamespaces()( namespaces []Namespace,err error)  {
	ns, err := clientset.CoreV1().Namespaces().List(metav1.ListOptions{})
	if err != nil {
		fmt.Println("k8s get node err is ",err)
	}
	for _,n := range ns.Items {
		//fmt.Println(n.Name)
		fmt.Println(n.Status.Phase)
		fmt.Println(n.CreationTimestamp.Format("2006-01-02"))
		namespaces = append(namespaces,Namespace{
			Name: n.Name,
			Staus: string(n.Status.Phase),
			CreateDate: n.CreationTimestamp.Format("2006-01-02"),
		})
	}
	return
}

type Deployment struct {
	Name string						`json:"name"`
	Labels map[string]string		`json:"labels"`
	ContainerGroup string			`json:"containergroup"`
	TempImage []string				`json:"tempimage"`
	CreateDate string		`json:"createdate"`
}

func GetKubernetesNamespaceDetail(name string)(dps []Deployment,svcs []Services ,events []Event,configmaps []K8sConfitMap,secrets []K8sSecret,jobs []K8sJob,sts []K8sStatefulset,pvcs []K8sPersistentVolumeClaim,daemonsets []K8sDaemonset, err error)  {
	//dp, err := clientset.CoreV1().ReplicationControllers(name).List(metav1.ListOptions{})
	dps,_ = getDeployments(name)
	svcs,_ = getService(name)
	events,_ =getEvents(name)
	configmaps,_ = getConfigmapList(name)
	secrets,_ = getSecretList(name)
	jobs,_ = getJobs(name)
	sts,_ = getStatefulsets(name)
	pvcs,_ = getPersistentVolumeClaim(name)
	daemonsets,_ = getDaemonsets(name)

	return

}

func getDeployments(name string)(dps []Deployment, err error)  {
	dp,_ := clientset.AppsV1().Deployments(name).List(metav1.ListOptions{})
	//fmt.Printf("%+v\n",dp)
	for _,d := range dp.Items {
		var imsges []string
		for _,c := range  d.Spec.Template.Spec.Containers {
			imsges = append(imsges,c.Image)
		}

		dps = append(dps,Deployment{
			Name: d.Name,
			Labels: d.Labels,
			ContainerGroup: fmt.Sprintf("%d / %d",d.Status.ReadyReplicas,d.Status.Replicas),
			TempImage: imsges,
			CreateDate: d.CreationTimestamp.Format("2006-01-02"),
		})
		//fmt.Printf("%+v\n",d.)
	}
	return
}

type Services struct {
	Name string				`json:"name"`
	Selector []string			`json:"selector"`
	ClusterIp string		`json:"clusterip"`
	DomainName string		`json:"demainname"`
	EndPoints []string		`json:"endpoints"`
	CreateDate string		`json:"createdate"`
}


func getService(name string)(svcSlice []Services, err error)  {
	svcs,_ := clientset.CoreV1().Services(name).List(metav1.ListOptions{})
	//fmt.Printf("%+v\n",dp)

	for _,svc := range svcs.Items {
		var epSlice []string
		var labelstr []string
		for k,v := range svc.Spec.Selector {
			tmpstr := k + ": " + v
			labelstr = append(labelstr,tmpstr)
		}


		endpoint,err := clientset.CoreV1().Endpoints(name).List(metav1.ListOptions{})
		if err != nil {
			log.Println(err.Error())
		}
		var podip []string
		var nodename []string
		for _,ep := range  endpoint.Items {

			if strings.TrimSpace(svc.Name) == strings.TrimSpace(ep.Name) && strings.TrimSpace(ep.Name) != "kubernetes" && len(ep.Subsets) > 0 {
				//后端podIP只取一个，如果多个replics，怎么处理？
				//podip = ep.Subsets[0].Addresses[0].IP //获取service后端podIp
				//nodename = *ep.Subsets[0].Addresses[0].NodeName



				for _,subaddress := range ep.Subsets[0].Addresses {

					podip = append(podip,subaddress.IP)
					nodename = append(nodename,*subaddress.NodeName)
				}

				break    //get 如何传入参数
			}
		}

		fmt.Println(nodename,podip,"lalalal")

		var internalPort int32
		for _,p := range svc.Spec.Ports {
			if len(nodename) != 0 {
				for i,n := range nodename {
					internalPort = p.Port
					epSlice = append(epSlice, svc.Spec.ClusterIP+":"+strconv.Itoa(int(p.Port))+"→"+podip[i]+":"+p.TargetPort.String()+" ( "+n+" ) ")
				}

			} else {
				//epSlice = append(epSlice, svc.Spec.ClusterIP+":"+strconv.Itoa(int(p.Port))+"→"+podip+":"+p.TargetPort.String())
				epSlice = append(epSlice, "null")
			}
		}
		tmsvc := Services{
			Name: svc.Name,
			Selector: labelstr,
			ClusterIp: svc.Spec.ClusterIP ,
			DomainName:svc.Name + "." + svc.Namespace + fmt.Sprintf(":%d",internalPort),
			EndPoints: epSlice,
			CreateDate: svc.CreationTimestamp.Format("2006-01-02 "),

		}

		svcSlice = append(svcSlice,tmsvc)


	}
	return
}





func getEvents(name string)(ev []Event, err error)  {
	fmt.Println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
	events,_ := clientset.CoreV1().Events(name).List(metav1.ListOptions{})
	//fmt.Printf("%+v\n",dp)
	//svcSlice := []Services{}

	for _,item := range events.Items {

		ev = append(ev,Event{
			Name: item.Name,
			Kind: item.InvolvedObject.Kind,
			ChildObject: item.InvolvedObject.FieldPath,
			Num: item.Count,
			Type: item.Type,
			Source: item.Source.Component + " " + item.Source.Host,
			Message: item.Message,
			Reason: item.Reason,
			LastOccurTime: item.LastTimestamp.Format("2006-01-02 15:04:05"),
		})
	}


	return
}

